module.exports = function(sequelize, DataTypes) {
  var Tag = sequelize.define(
    'Tag',
    {
      name: {
        type: DataTypes.STRING(100),
        comment: 'Name of the tag'
      },
      isFolder: {
        type: DataTypes.BOOLEAN,
        defaultValue: false,
        comment: 'The tag is a folder or not'
      },
      show: {
        type: DataTypes.INTEGER,
        defaultValue: -1,
        comment:
          'Show order of the tag, -1: invisible, 0: normal, > 0: pinned order desc'
      },
      folderId: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        comment: 'Parent folder of the tag'
      },
      searchCount: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        comment: 'Search count of the tag, order by desc'
      }
    },
    {
      tableName: 'tags',
      paranoid: true,
      indexes: [
        {
          name: 'folder_id_idx',
          fields: ['folderId']
        },
        {
          name: 'is_folder_idx',
          fields: ['isFolder']
        },
        {
          name: 'show_idx',
          fields: ['show']
        },
        {
          name: 'search_count_idx',
          fields: ['searchCount']
        }
      ],
      comments: 'Tags for Documents'
    }
  )

  Tag.associate = function(models) {
    this.belongsTo(models.User, {
      as: 'Owner',
      foreignKey: 'userId',
      constraints: false
    })
    this.belongsTo(models.Tag, {
      as: 'Folder',
      foreignKey: 'folderId',
      constraints: false,
      defaultValue: 0
    })
    this.belongsToMany(models.Document, {
      as: 'DocumentTags',
      through: 'DocumentTag',
      foreignKey: 'tagId'
    })
  }
  return Tag
}
